/**
 * Created by PhpStorm.
 * User:  iyahe@qq.com (天明)
 * Date: 2019/8/1 0001
 * Time: 下午 14:18
 * Description:
 */
import React from 'react';
import md5 from 'md5'
import {format} from 'timeago.js'
import {Button, Table, Pagination, Tabs, Message} from 'element-react';
import $http from '../../api/http'
import cache from '../../plugin/cache'

export default class homeDaili extends React.Component {
	constructor(props) {
		super(props)
		let that = this
		this.state = {
			columns: [
				{
					label: "名称",
					prop: "come",
					width: 150
				},
				{
					label: "IP",
					prop: "proxy",
					width: 220,
					sortable: true
				},
				{
					label: "地址",
					prop: "address"
				},
				{
					label: "更新时间",
					width: 120,
					sortable: true,
					render: function (row) {
						return (
							format(row.updateTime, 'zh_CN')
						)
					}
				},
				{
					label: "操作",
					prop: "address",
					render: function (row, column, index) {
						let btnGruop;
						if (parseInt(row.check_result) > 0) {
							if (row.check_result === 1) {
								btnGruop = (
									<Button type="success" size="small" icon="circle-check"
													onClick={that.checkOnce.bind(that, row, index)}>成功</Button>
								)
							}
							if (row.check_result === 2) {
								btnGruop = (
									<Button type="danger" size="small" icon="circle-close"
													onClick={that.checkOnce.bind(that, row, index)}>失败</Button>
								)
							}
						} else {
							btnGruop = (
								<Button type="warning" size="small" icon="loading">验证</Button>
							)
						}
						return (
							<span className="btnGroup">
								{btnGruop}
								<Button type="info" size="small" icon="date" onClick={that.deleteRow.bind(that, row)}>复制</Button>
								{
									that.state.select ? <span onClick={that.newFavAdd.bind(that, row, index)} style={{marginLeft: '10px'}}>
									{row.fav === 1 ?
										<Button type="success" size="small" icon="star-on">取消</Button>
										:
										<Button type="default" size="small" icon="star-off">选择</Button>
									}
								</span> : ''
								}
							</span>
						)
					}
				}
			],
			data: [],
			total: {
				pageSize: 12,
				count: 0
			},
			select: false
		}
		this.getList();
		window.selectDaili = []
	}

	render() {
		const pageList = (
			<Table
				style={{width: '100%'}}
				columns={this.state.columns}
				data={this.state.data}
				border={true}
				onSelectChange={this.selectAll.bind(this)}
				onSelectAll={this.selectAll.bind(this)}
				stripe={true}
				onSortChange={this.handleSort.bind(this)}
			/>
		);
		return (
			<div className="dl">
				{
					this.state.select ? <div style={{margin: '10px 0', textAlign:'right'}}>
						<Button type="info" onClick={() => this.props.history.push({
							pathname: '/yali',
							state: {
								model: 2
							}
						})}>返回压力测试</Button>
					</div> : ''
				}
				<Tabs type="border-card" activeName="0" onTabClick={this.onTabClick.bind(this)}>
					<Tabs.Pane label="全部代理" name="0"> {pageList} </Tabs.Pane>
				</Tabs>
				<div className="page" style={{
					textAlign: 'center',
					marginTop: '20px'
				}}>
					<div className="block">
						<Pagination
							layout="total, prev, pager, next"
							onCurrentChange={this.getList.bind(this)}
							pageSize={this.state.total.pageSize}
							total={this.state.total.count}/>
					</div>
				</div>
			</div>
		)
	}

	handleSort(data) {
	}

	getList(page = 1) {
		$http.post('store/proxy/find.html', {
			limit: this.state.total.pageSize,
			page: page
		}).then(res => {
			if (res.code === 200) {
				this.setState({
					data: res.data.list,
					columns: this.state.columns,
					total: {
						count: res.data.count,
						pageSize: this.state.total.pageSize,
					}
				})
				setTimeout(() => {
					this.checkProxy()
				})
			}
		})
	}

	checkProxy() {
		this.state.data.map((val, index) => {
			this.collection(val, index); //是否收藏判断
			this.checkProxyFun(val, index)
		})
	}

	checkProxyFun(val, index) {
		const remote = window.electron.remote;
		let testUrl = 'https://www.baidu.com/';
		remote.app.proxyTest(testUrl, 'http://' + val.proxy)
		.then((res, body, head) => {
			this.setProxy(index, 'check_result', 1)
		}).catch(e => {
			this.setProxy(index, 'check_result', 2)
		});
	}

	// TODO tab切换
	onTabClick(event) {
		let id = parseInt(event.key.substr(1, 1));
		console.log(id)
		if (id === 0) {
			this.getList()
		}
		if (id === 1) {
			let list = cache.default.get('check_success');
			if (!list) list = {};
			this.setState({
				data: list,
				columns: this.state.columns,
				total: {
					count: list.length,
					pageSize: 1000,
				}
			});
			this.checkProxy()
		}
		if (id === 2) {
			let list = cache.default.get('favList')
			console.log(list)
		}
	}

	// TODO 设置选中
	setProxy(index, key, check_result) {
		this.setState({
			data: this.state.data.map((item, _index) => _index === index ? {...item, [key]: check_result} : item)
		});
	}

	// TODO 是否收藏
	collection(val, index) {
		let key = 'favList';
		let favList = cache.default.get(key);
		if (favList && favList.indexOf(md5(val['proxy'])) >= 0) {
			this.setProxy(index, 'fav', 1)
		} else {
			this.setProxy(index, 'fav', 0)
		}
	}

	deleteRow(row) {
		const clipboard = window.electron.clipboard;
		clipboard.writeText(row.proxy)
		Message({
			message: '已复制到剪贴板',
			type: 'success'
		});
	}

	newFavAdd(row, index) {
		let favList = cache.default.get('favList');
		let key = md5(row.proxy);
		let status = 0;
		let position = favList ? favList.indexOf(key) : -1;
		if (position < 0) {
			if (!favList) favList = [];
			favList.push(row.proxy);
			status = 1
		} else {
			favList = favList.slice(position, 1)
			status = 0
		}
		cache.default.set('favList', favList)
		Message({
			message: (status === 1) ? '已选择' : '取消选择',
			type: 'success'
		});
		this.setProxy(index, 'fav', status)
	}

	// TODO 单条判断
	checkOnce(row, index) {
		this.setProxy(index, 'check_result', '')
		this.checkProxyFun(row, index)
	}

	selectAll(selection) {
		selection.map((val) => {
			window.selectDaili.push(val)
		});
		let len = window.selectDaili.length;
		Message({
			message: '已选择' + len + '个',
			type: 'success'
		});
	}

	componentDidMount() {
		let search = this.props.location.search;
		if (search.indexOf('model') >= 0) {
			Message({
				message: '请勾选即将使用的代理IP',
				type: 'success'
			});
			this.setState({
				select: !this.state.select
			});
		}
	}
}
